package com.glsc.ngateway.platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Flow;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowMetaTable;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.oaflow.TOaFlowMetaTableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WorkflowService {


    @Autowired
    private TOaFlowMetaTableRepository tOaFlowMetaTableRepository;


    // t_oa_flow_meta_table 增删改查
    public Page<TOaFlowMetaTable> getFlowMetaData(String workFlowId, String interfaceFieldName, Integer page, Integer size) {
        Sort.Direction direction = Sort.Direction.ASC;
        String sort = "fieldType";
        Pageable pageable = PageRequest.of(page - 1, size, direction, sort);

        TOaFlowMetaTable fmd = new TOaFlowMetaTable();
        fmd.setWorkFlowId(workFlowId);
        Example<TOaFlowMetaTable> example = Example.of(fmd);
        if (!interfaceFieldName.equals("")) {
            fmd.setFlowFieldName(interfaceFieldName);
        }
        return tOaFlowMetaTableRepository.findAll(example, pageable);
    }

    @Transactional
    public TOaFlowMetaTable add(TOaFlowMetaTable fmd) {
        if (fmd.getId() != null) {
            throw PlatformException.error("新增流程字段不要输入id");
        }
        return tOaFlowMetaTableRepository.save(fmd);
    }

    public int deleteFlowMetaData(String workFlowId, String interfaceFieldName) {
        if (interfaceFieldName.equals(""))
            return tOaFlowMetaTableRepository.deleteByWorkFlowId(workFlowId);
        else
            return tOaFlowMetaTableRepository.deleteByFieldName(workFlowId, interfaceFieldName);
    }

    @Transactional
    public void update(Object param) {

        Map<String, Object> map = (Map) JSON.toJSON(param);
        List<Long> ids = new ArrayList<>();
        String workFlowId = "";

        for (int i = 0; i < map.size(); i++) {
            JSONObject obj = JSON.parseObject(map.get(String.valueOf(i)).toString());
            TOaFlowMetaTable fmd = JSONObject.toJavaObject(obj, TOaFlowMetaTable.class);
            if (i == 0) workFlowId = fmd.getWorkFlowId();
            fmd = tOaFlowMetaTableRepository.save(fmd);
            ids.add(fmd.getId());
        }
        if (ids.size() > 0)
            tOaFlowMetaTableRepository.deleteById(ids, workFlowId);

//        if (fmd.getId() == null) {
//            throw GlamException.error("流程字段id不能为空");
//        }
//        FlowMetaData existed = flowMetaDataRepo.findExist(fmd.getId());
//        if (existed == null) {
//            throw GlamException.error("未找到id=" + fmd.getId() + "的流程字段");
//        }
//        return flowMetaDataRepo.save(fmd);
    }

    public Page<Flow> queryFlow(Integer page, Integer size, String flowName){
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Map<String,String>> flowMetaDataPage = tOaFlowMetaTableRepository.queryFlow(pageable, flowName);

        List<Flow> resultList = flowMetaDataPage.getContent().stream().map(h -> {
            Flow flow = new Flow();
            flow.setWorkFlowId(h.get("workFlowId"));
            flow.setFlowName(h.get("flowName"));
            flow.setFields(tOaFlowMetaTableRepository.getById(h.get("workFlowId")));
            return flow;
        }).collect(Collectors.toList());
        return new PageImpl<>(resultList, pageable, flowMetaDataPage.getTotalElements());
    }
    public Page getAllFlow(Integer page, Integer size) {
        Sort.Direction direction = Sort.Direction.ASC;
        String sort = "cast(workFlowId as integer)";
        Pageable pageable = PageRequest.of(page - 1, size, JpaSort.unsafe(direction, sort));

        List<Flow> flows = new ArrayList<>();
        List<TOaFlowMetaTable> list = tOaFlowMetaTableRepository.getAllFlow();
        int flowNum = list.size();
        for (int i = 0; i < flowNum; i++) {
            String workFlowId = list.get(i).getWorkFlowId();
            flows.add(new Flow());
            flows.get(i).setWorkFlowId(workFlowId);
            flows.get(i).setFlowName(list.get(i).getFlowName());
            flows.get(i).setFields(tOaFlowMetaTableRepository.getById(workFlowId));
        }

        int totalElements = list.size();
        int fromIndex = pageable.getPageSize() * pageable.getPageNumber();
        int toIndex = pageable.getPageSize() * (pageable.getPageNumber() + 1);
        if (toIndex > totalElements) toIndex = totalElements;

//        Page<FlowMetaData> fpage =  flowMetaDataRepo.getAllFlow(pageable);

//        Page newpage = new PageImpl(flows,pageable,flowNum);
        List<Flow> indexObjects = flows.subList(fromIndex, toIndex);
        Page<Flow> newpage = new PageImpl<>(indexObjects, pageable, totalElements);
        return newpage;
    }

}
